﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class CameraRayCast : MonoBehaviour {
    private Camera mainCamera;
    public List<Renderer> changedTrees = new List<Renderer>();
    public List<Renderer> newChangingdTrees = new List<Renderer>();
    public List<Renderer> emptyList = new List<Renderer>();
    public LayerMask layerMask;
    public int frameCount;
    public int frameLoopMax = 3;
    public Material transparentMaterial;
    public Material normalMaterial;
    public static CameraRayCast instance;
    private Transform hero;

    void Awake()
    {
        instance = this;
    }
    // Use this for initialization
    public void SetHero (Transform hero)
    {
        this.hero = hero;	
	}

	// Update is called once per frame,i would 
	void Update () {
        if(hero != null)
        {
            frameCount ++;
            frameCount = frameCount % frameLoopMax;
            if(frameCount < frameLoopMax - 1) return;
            RaycastHit[] hits;
            Vector3 dir = hero.transform.position - transform.position;
            hits = Physics.RaycastAll (transform.position, dir, 100.0f,layerMask);

            // Change the material of all hit colliders
            // to use a transparent Shader
            for (int i = 0;i < hits.Length; i++) {
                RaycastHit hit= hits[i];
                Renderer renderer =  hit.collider.renderer;
                if (renderer) {
                    renderer.material = transparentMaterial;
                    newChangingdTrees.Add(renderer);
                }
            }

            //get rid of non-transparent one
            for(int j=0;j<changedTrees.Count;j++)
            {
                if(!newChangingdTrees.Contains(changedTrees[j]))
                {
                    changedTrees[j].material = normalMaterial;
                }
            }

            //exchange tree list
            emptyList = changedTrees;
            changedTrees = newChangingdTrees;
            newChangingdTrees = emptyList;
            newChangingdTrees.Clear();
        }
	}
}
